package com.my.netty.basic.echoserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

/*
    netty入门最终练习，实现一个回声服务器，即客户端给服务器发什么数据，服务端就给客户端返回什么数据
 */
@Slf4j
public class EchoServer {

    public static void main(String[] args) {
        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel sc) throws Exception {
                        log.info("客户端{}已连接", sc.remoteAddress());
                        sc.pipeline()
                                .addLast(new StringDecoder())
                                .addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        log.info("收到{}:{}", sc.remoteAddress(), msg);

                                        ByteBuf buffer = ctx.alloc().buffer();
                                        buffer.writeBytes(((String) msg).getBytes());
                                        sc.writeAndFlush(buffer);

                                        //不要释放，不然报错
//                                        buffer.release();
                                    }
                                });
                    }
                }).bind(8080);
        log.info("服务端已启动..");
    }
}
